trigger JobAppSharingTrigger on Job_Application__c (after insert, after update) {

	//TODO: Instatiate two job application lists called "interviewJobApps" and "nonInterviewJobApps"
	List<Job_Application__c> interviewJobApps = new List<Job_Application__c>();
	List<Job_Application__c> nonInterviewJobApps = new List<Job_Application__c>();

	//TODO: Create a for loop to loop through the triggering job applications
	for (Job_Application__c jobApp : Trigger.new){

		//TODO: If the job application stage = "Schedule Interviews" and it was not set to that value before, then add the record to the interviewJobApps list
		//if ((Trigger.isUpdate) && (jobapp.stage__c == 'Schedule Interviews') && (Trigger.oldMap.get(jobapp.id).stage__c != 'Schedule Interviews')){
		if ((Trigger.isUpdate) && (jobapp.stage__c == '面接調整中') &&
			(Trigger.oldMap.get(jobapp.id).stage__c != '面接調整中')){
			interviewJobApps.add(jobapp);
		}
		// else if ((Trigger.isInsert) && (jobapp.stage__c == 'Schedule Interviews') ) {
		else if ((Trigger.isInsert) && (jobapp.stage__c == '面接調整中') ) {
			interviewJobApps.add(jobapp);
		}
		//TODO: If not, and the stage is not "Schedule Interviews" then add it to the nonInterviewJobApps list
		// else if (jobApp.Stage__c != 'Schedule Interviews') {
		else if (jobApp.Stage__c != '面接調整中') {
			nonInterviewJobApps.add(jobApp);
		}
	}
	//TODO: Call the appropriate method from the JobAppSharing class to add sharing for the records in the interviewJobApps list
	JobAppSharing.createSharing(interviewJobApps,'Position_Interviewer__c','Edit');

	//TODO: Then change the sharing for the nonInterviewJobApps to read-only
	JobAppSharing.createSharing(nonInterviewJobApps,'Position_Interviewer__c','Read');

	if (Trigger.isInsert){
		// Share with position hiring manager if available
		List<Job_Application__c> jobApps = [select position__c,candidate__c,position__r.hiring_manager__c from Job_Application__c where ID IN :Trigger.newMap.keySet() and position__r.hiring_manager__c != null];
		JobAppSharing.createSharing(jobApps,'Hiring_Manager__c','Edit');
	}
}